package com.cloudeasy.user.service.expand;

import com.cloudeasy.api.constant.AmqpConstant;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class AuthCodeService {
    private final StringRedisTemplate stringRedisTemplate;

    public AuthCodeService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 保存验证码
     *
     * @param suffix   后缀
     * @param authCode 验证码
     */
    public void save(String suffix, String authCode) {
        stringRedisTemplate.opsForValue().set(String.format(AmqpConstant.SmtpConstant.AUTH_CODE_PERFIX, suffix), authCode, 5, TimeUnit.MINUTES);
    }

    /**
     * 获取验证码
     *
     * @param suffix 后缀
     * @return 验证码
     */
    public String get(String suffix) {
        return stringRedisTemplate.opsForValue().get(String.format(AmqpConstant.SmtpConstant.AUTH_CODE_PERFIX, suffix));
    }

    /**
     * 校验验证码
     *
     * @param suffix   后缀
     * @param authCode 验证码
     * @return {@link Boolean}
     */
    public Boolean matches(String suffix, String authCode) {
        return Objects.equals(get(suffix), authCode);
    }

    public void remove(String suffix) {
        stringRedisTemplate.delete(String.format(AmqpConstant.SmtpConstant.AUTH_CODE_PERFIX, suffix));
    }
}
